package org.zdd.bookstore.model.service.impl;

import org.springframework.stereotype.Service;
import org.zdd.bookstore.common.pojo.BSResult;
import org.zdd.bookstore.common.utils.BSResultUtil;
import org.zdd.bookstore.model.dao.CommentMapper;
import org.zdd.bookstore.model.dao.UserMapper;
import org.zdd.bookstore.model.dao.UserRoleMapper;
import org.zdd.bookstore.model.entity.Comment;
import org.zdd.bookstore.model.entity.User;
import org.zdd.bookstore.model.entity.UserRole;
import org.zdd.bookstore.model.service.ICommentService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public  class CommentServiceImpl implements ICommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Comment> findById(Integer bookId) {
        List<Comment> comments = commentMapper.selectById(bookId);
        return comments;
    }



    /**
     * 添加评论
     * @param comment
     * @return
     */
    @Override
    public Integer addComment(Comment comment) {
        if (comment == null){
            BSResultUtil.build(400,"评论为空");
        }
        String username = comment.getUsername();
        User user =userMapper.selectByName(username);
        Integer userId=user.getUserId();
        Integer bookId = comment.getBookId();
        String content = comment.getContent();
        Date date=new Date();
        Integer i = commentMapper.addComment(userId,username,bookId,content,date);
        commentMapper.selectById(bookId);
        return i;
    }

    /**
     * 删除评论
     * @param commentId
     * @return
     */
    @Override
    public BSResult deleteComment(Integer commentId) {
        Integer i = commentMapper.deleteComment(commentId);
        if (i <= 0 ){
            return BSResultUtil.build(400,"删除失败！");
        }
        return BSResultUtil.success();
    }

    /**
     * 查询bookId
     * @param commentId
     * @return
     */
    @Override
    public Integer selectBookId(Integer commentId) {
        Comment comment = commentMapper.selectBookId(commentId);
        Integer bookId = comment.getBookId();
        return bookId;
    }

    /**
     * 检查是否为管理员
     * @param commentId
     * @return
     */
    @Override
    public Integer selectIsAdmin(Integer commentId) {
        Comment comment = commentMapper.selectUserId(commentId);
        Integer userId = comment.getUserId();
        UserRole userRole = userRoleMapper.selectIsAdmin(userId);
        Integer roleId = userRole.getRoleId();
        return roleId;
    }

//    /**
//     * 根据RoleId 判断是否为管理员
//     * @return
//     */
//    public Integer isAdmin(Integer roleId) {
//        User user = (User) SecurityUtils.getSubject();
//        Integer userId = user.getUserId();
//        UserRole role =  commentMapper.selectIsAdmin(userId,roleId);
//        return role.getRoleId();
//    }
}
